import LC from 'leancloud-storage';

let create = (title,author,price = 0.0, image = '', description = '') => {
  return new Promise((resolve, reject) => {
    let Book = LC.Object.extend('Book');   // 创建 Product 对象
    let book = new Book();                 // 实例化 product
    let currentUser = LC.User.current();         // 获取当前用户
    let name = image.name;
    let imageFile = new LC.File(name, image);    // 创建(上传)文件对象
    book.set('title', title);
	book.set('author', author);
    book.set('price', price);
    book.set('description', description);
    book.set('owner', currentUser);
    book.set('image', imageFile);
    book
      .save()
      .then(resp => {
        console.log("Created a product: ", resp);
        resolve(resp);                         // 操作成功，返回
      }, error => {
        console.log(JSON.stringify(error));
        reject(JSON.stringify(error))          // 操作失败
      })
      .catch(error => {
        console.log(JSON.stringify(error));
        reject(JSON.stringify(error))          // 操作失败
      });
  });
};

let getBooks = (skip = 0, limit = 20) => {
  return new Promise((resolve, reject) => {
    let bookQuery = new LC.Query('Book');
    bookQuery
      // .select(['-description'])
      .include('owner', 'image')
      // 按 createdAt 降序排列
      .descending('createdAt')
      .skip(skip)
      .limit(limit)
      .find()
      .then(products => {
        console.log(products);
        resolve(products);
      }).catch(error => {
        reject(error);
      });
  });
};

let getBookById = (id) => {
  return new Promise((resolve, reject) => {
    let bookQuery = new LC.Query('Book');

    // get 方法，通过 objectId 获取对象
    bookQuery.include('owner', 'image')
      .get(id)
      .then(prod => {
        console.log(prod.toJSON);
        resolve(prod);
      }).catch(error => {
        console.log(error);
        reject(error);
      });
  });
};

function deleteBookById(id) {
  let book = LC.Object.createWithoutData('Book', id);
  return new Promise((resolve, reject) => {
    book.destroy()
      .then(resp => {
        console.log("deleted, ", resp);
        resolve(resp);
      })
      .catch(error => {
        console.log(error);
        reject(error);
      });
  });
};
// 修改记录, data 包含要修改的值
 function update(id, data) {
        return new Promise((resolve, reject) => {
            let book = LC.Object.createWithoutData('Book', id);
            book.set(data);
            book.save()
                .then(resp => {
                    console.log('update(id):', resp);
                    resolve(resp)
                })
                .catch(error => {
                    console.log('update(id):', error);
                    reject(error)
                });
        });
    };

// 批量删除记录，data 为包含批量操作记录的数组
 let deleteAll = (data)  => {
        return new Promise((resolve, reject) => {
            // 获取所有待删除记录的id
            let ids = data.map(item=>{return item.id});
            let query = new LC.Query('Book'); 
            query.containedIn('objectId',ids)  // 使用id 把所有要删除的记录打出来
            .destroyAll()          // 执行批量删除操作
                .then(resp => {
                    console.log('deletaAll(data):', resp);
                    resolve(resp);
                })
                .catch(error => {
                    console.log('deletaAll(data):', error);
                    reject(error);
                });
        });
    };

let getBookCount = () => {
  let bookQuery = new LC.Query('Book');
  return new Promise((resolve, reject) => {
    bookQuery.count()
      .then(count => {
        console.log("count: ", count);
        resolve(count);
      })
      .catch(error => {
        console.log(error);
        reject(error);
      });
  });

};

export default {
  create,
  getBooks,
  getBookById,
  deleteBookById,
  getBookCount,
  deleteAll,
  update,
}

